package com.tuijian.service.rearrange;

import com.alibaba.fastjson.JSON;
import com.tuijian.util.HbaseUtils;
import com.tuijian.util.RedisUtils;
import com.tuijian.vo.Post;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


/**
 * 帖子重排类
 * @author jiaqingbo
 */
@Service
public class PostRearRange {
    /**
     * RedisUtils对象
     */
    @Resource
    private RedisUtils redisUtils;

    /**
     * HbaseUtils对象
     */
    @Resource
    private HbaseUtils hbaseUtils;
    /**
     * 帖子重排方法
     * @param postList 精排排序list
     * @param userId 多样性参数0~1
     * @return 重排排序list
     */
    public void rearRange(List<Post> postList,String userId){
        List<String> postIdList = new ArrayList<>();


        //最终得分
        for(int i = 0; i < postList.size(); i++){
            postList.get(i).setScore(postList.get(i).getScore1() * 0.2 + postList.get(i).getScore2() * 0.8);
        }
        //根据分数排序
        Collections.sort(postList, new Comparator<Post>() {
            @Override
            public int compare(Post o1, Post o2) {
                return o2.getScore().compareTo(o1.getScore());
            }
        });
        for(int i = 0; i < postList.size(); i++){
            postIdList.add(postList.get(i).getPostId());
        }
        //写入redis
        redisUtils.setCacheNewList("post" + userId,postIdList);
        // 获取存储的数据并输出
        //System.out.println("redis 存储的字符串为: "+ jedis.get(new_cisList.get(0).getUserId()));

        //写入hbase
        try {
            //连接位置
            hbaseUtils.connect("hadoop1,hadoop2,hadoop3","2181");
            Map map=new HashMap();
            //列名统一为info
            map.put("info", JSON.toJSONString(postIdList));
            //表名rearrange，rowkey为用户id，列族名为range，map为信息
            hbaseUtils.put("rearrange",userId,"range",map);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                hbaseUtils.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
